#!/usr/bin/env bash

set -o errexit
set -o nounset
set -o xtrace # can remove this later, for now it's nice to see commands

if [ "$#" -ne 1 ]; then
    cat << EOM
Expected one command line argument: the name of an initially-empty working
directory for sources, binaries, and reports.
EOM
    exit -1
fi

OS="$(uname -s)"

WORK=$1

if [[ "$OS" == "Linux" ]]; then
    CORES="$(nproc)"
elif [[ "$OS" == "Darwin" ]]; then
    CORES="$(sysctl -n hw.logicalcpu)"
else # default
    CORES=1
fi

ALIVECC=@PROJECT_BINARY_DIR@/alivecc
JOBSERVER=@PROJECT_BINARY_DIR@/alive-jobserver
ALIVEPP=@LLVM_BINARY_DIR@/bin/clang++ # don't use alive for C++ until we support exceptions!

export ALIVECC_OVERWRITE_REPORTS=1
export ALIVECC_SUBPROCESS_TIMEOUT=600
export ALIVECC_SMT_TO=30000
export ALIVECC_DISABLE_UNDEF_INPUT=1
export ALIVECC_REPORT_DIR=$WORK/report
export ALIVECC_QUIET=1
export ALIVECC_MAX_MEM=1000000 # we'll just let ulimit take care of this

cd $WORK
git clone https://github.com/llvm/llvm-test-suite.git test-suite

mkdir test-suite-build
cd test-suite-build
cmake -DCMAKE_C_FLAGS=-mlong-double-64 -DCMAKE_C_COMPILER=$ALIVECC -DCMAKE_CXX_COMPILER=$ALIVEPP -C../test-suite/cmake/caches/O3.cmake ../test-suite -DTEST_SUITE_SUBDIRS="MicroBenchmarks;SingleSource"

# 5 GB
ulimit -m 5000000 -v 5000000

# intentionally limit make-level parallelism to < number of cores
time $JOBSERVER -j$CORES make -j$CORES

echo Normal termination.
